import Vue from 'vue'
import VueRouter from 'vue-router'
import DataRouter from './datastatistics'
import CardNumberManagementRouter from './cardnumbermanagement'
import BackManagementRouter from './backmanagement'
import FinancialManagementRouter from './financialmanagement'
import SystemManagementRouter from './systemmanagement'
import BigCustomerRouter from './bigcustomer'
const login = () => import( /* webpackChunkName: "login" */ "../views/Login/Login.vue")
const home = () => import( /* webpackChunkName: "home" */ "../views/index/Index.vue")
import { getApiroot } from "../api/roleRoot"

// 页面加载进度条
import NProgress from 'nprogress'

Vue.use(VueRouter)

const routes = [
  {
    path: '',
    redirect: '/login'
  },
  { // 登录
    path: '/login',
    name: 'login',
    component: login,
  },
  {
    path: '/datas',
    name: 'home',
    component: home,
    children: [
      ...DataRouter,
      ...CardNumberManagementRouter,
      ...BackManagementRouter,
      ...FinancialManagementRouter,
      ...BigCustomerRouter,
      ...SystemManagementRouter,
    ]
  },
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  // 每次切换页面时，调用进度条
  NProgress.start();

  let userMsg
  try {
    userMsg = JSON.parse(localStorage.userInfo)
  } catch {
    userMsg = ''
  }
  if (to.path == '/login') {
    next()
  } else {
    if (to.path == '/login' || userMsg) {
      getApiroot({
        id: userMsg.root
      }).then(res => {

        let obj = {
          userImg: userMsg.userImg,
          username: userMsg.username,
          root: userMsg.root,
          nickname: userMsg.nickname
        }
        router.app.$store.commit("getUsermsg", obj)
        router.app.$store.commit("getUserRoot", res.data)
      })
      next()
    } else {
      alert('请登录')
      next(false)// 指定去哪个路由
    }
  }
})

router.afterEach((to, from) => {
  // 在即将进入新的页面组件前，关闭掉进度条
  NProgress.done()
  console.log("我是后置钩子");
  if (to.meta.title) {
    document.title = to.meta.title
  }
});

export default router
